package com.example.aoplog.aspect;

import com.example.aoplog.annotation.LogAnnotation;
import com.example.aoplog.mapper.LogMapper;
import com.example.aoplog.pojo.Log;
import lombok.extern.slf4j.Slf4j;
import org.aopalliance.intercept.Joinpoint;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @author achen
 * @create 2021-10-26 16:51
 */
@Aspect
@Configuration
@Slf4j
public class LogAspect {
    @Autowired
    private LogMapper logMapper;

    @After("@annotation(com.example.aoplog.annotation.LogAnnotation)")
    public void logAfterAspect(JoinPoint joinPoint) {
        Log log = new Log();
        log.setLog_date(new Date());
        log.setUsername("admin");

        //获取ip
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes)
                        RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String ip = getRemoteIP(request);
        log.setLog_ip(ip);

        //获取方法签名对象
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //通过方法签名对象获取方法对象
        Method method = signature.getMethod();
        //通过方法对象获取方法上的注解
        LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);

        log.setLog_content(logAnnotation.content());
        log.setLog_type(logAnnotation.type());

        //添加日志
        logMapper.addLog(log);

        System.out.println(log.toString());
    }
    /**
     * 获取访问IP地址
     *
     * @param request
     * @return
     */
    protected String getRemoteIP(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");

        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        int index = ip.indexOf(",");
        if (index != -1) {
            return ip.substring(0, index);
        } else {
            return ip;
        }
    }


}
